#!/usr/bin/env bun

import { prisma } from '../src/db'
import bcrypt from 'bcryptjs'

async function seedDatabase() {
  console.log('🌱 Seeding database...')

  try {
    // 1. 创建管理员账户
    console.log('👑 Creating admin account...')
    
    const adminEmail = 'admin@ordersystem.com'
    const adminPassword = 'admin123456'
    
    let admin = await prisma.user.findUnique({
      where: { email: adminEmail }
    })

    if (!admin) {
      const hashedPassword = await bcrypt.hash(adminPassword, 12)
      admin = await prisma.user.create({
        data: {
          email: adminEmail,
          username: 'admin',
          password: hashedPassword,
          role: 'ADMIN',
          isActive: true
        }
      })
      console.log('✅ Admin created:', adminEmail)
    } else {
      console.log('✅ Admin already exists:', adminEmail)
    }

    // 2. 创建子管理员账户
    console.log('👥 Creating sub-admin account...')
    
    const subAdminEmail = 'subadmin@ordersystem.com'
    const subAdminPassword = 'subadmin123456'
    
    let subAdmin = await prisma.user.findUnique({
      where: { email: subAdminEmail }
    })

    if (!subAdmin) {
      const hashedPassword = await bcrypt.hash(subAdminPassword, 12)
      subAdmin = await prisma.user.create({
        data: {
          email: subAdminEmail,
          username: 'subadmin',
          password: hashedPassword,
          role: 'SUB_ADMIN',
          isActive: true,
          createdByAdminId: admin.id
        }
      })
      console.log('✅ Sub-admin created:', subAdminEmail)
    } else {
      console.log('✅ Sub-admin already exists:', subAdminEmail)
    }

    // 3. 创建普通用户账户
    console.log('👤 Creating regular users...')
    
    const users = [
      {
        email: 'user1@example.com',
        username: 'user1',
        password: 'user123456'
      },
      {
        email: 'user2@example.com',
        username: 'user2',
        password: 'user123456'
      },
      {
        email: 'user3@example.com',
        username: 'user3',
        password: 'user123456'
      }
    ]

    for (const userData of users) {
      let user = await prisma.user.findUnique({
        where: { email: userData.email }
      })

      if (!user) {
        const hashedPassword = await bcrypt.hash(userData.password, 12)
        user = await prisma.user.create({
          data: {
            email: userData.email,
            username: userData.username,
            password: hashedPassword,
            role: 'USER',
            isActive: true
          }
        })
        console.log('✅ User created:', userData.email)
      } else {
        console.log('✅ User already exists:', userData.email)
      }
    }

    // 4. 创建一些示例充值记录
    console.log('💰 Creating sample recharge records...')
    
    const allUsers = await prisma.user.findMany({
      where: { role: 'USER' }
    })

    for (const user of allUsers) {
      const existingRecords = await prisma.rechargeRecord.count({
        where: { userId: user.id }
      })

      if (existingRecords === 0) {
        // 为每个用户创建2-3条充值记录
        const recordCount = Math.floor(Math.random() * 2) + 2
        
        for (let i = 0; i < recordCount; i++) {
          const amount = (Math.random() * 500 + 50).toFixed(2) // 50-550之间的随机金额
          const statuses = ['PENDING', 'COMPLETED', 'FAILED']
          const status = statuses[Math.floor(Math.random() * statuses.length)]
          
          const createdByNames = ['Alice Customer Service', 'Bob Support', 'Carol Admin', 'David Manager']
          const createdByName = createdByNames[Math.floor(Math.random() * createdByNames.length)]

          await prisma.rechargeRecord.create({
            data: {
              userId: user.id,
              amount: parseFloat(amount),
              status: status as any,
              orderId: `ORD-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
              paymentMethod: Math.random() > 0.5 ? 'Credit Card' : 'Bank Transfer',
              createdByUserId: admin.id, // 使用admin用户ID作为创建者
              createdByName: createdByName, // 随机的客服名称
              paymentChannel: Math.random() > 0.5 ? 'TOPPAY' : 'PAY668',
              transAccNo: `${Math.floor(Math.random() * 9000000000000000) + 1000000000000000}`, // 16位随机银行卡号
              paymentName: `Customer ${user.id}`,
              bankCode: Math.random() > 0.5 ? '001' : '002'
            }
          })
        }
        console.log(`✅ Created recharge records for user: ${user.email}`)
      }
    }

    // 5. 创建系统设置
    console.log('⚙️ Creating system settings...')
    
    const settings = [
      {
        key: 'SYSTEM_NAME',
        value: 'Order System',
        description: 'System display name'
      },
      {
        key: 'SYSTEM_VERSION',
        value: '1.0.0',
        description: 'Current system version'
      },
      {
        key: 'MAX_RECHARGE_AMOUNT',
        value: '10000',
        description: 'Maximum recharge amount per transaction'
      },
      {
        key: 'MIN_RECHARGE_AMOUNT',
        value: '10',
        description: 'Minimum recharge amount per transaction'
      },
      {
        key: 'GOOGLE_AUTH_ENABLED',
        value: 'true',
        description: 'Enable Google OAuth authentication'
      },
      {
        key: 'recharge_quick_amounts',
        value: '[100, 500, 1000, 2000, 5000, 10000]',
        description: '用户充值页面快捷金额选项配置'
      }
    ]

    for (const setting of settings) {
      const existing = await prisma.systemSetting.findUnique({
        where: { key: setting.key }
      })

      if (!existing) {
        await prisma.systemSetting.create({
          data: setting
        })
        console.log(`✅ Setting created: ${setting.key}`)
      } else {
        console.log(`✅ Setting already exists: ${setting.key}`)
      }
    }

    console.log('')
    console.log('🎉 Database seeding completed successfully!')
    console.log('')
    console.log('📋 Default Accounts:')
    console.log('👑 Admin: admin@ordersystem.com / admin123456')
    console.log('👥 Sub-Admin: subadmin@ordersystem.com / subadmin123456')
    console.log('👤 Users: user1@example.com, user2@example.com, user3@example.com / user123456')
    console.log('')
    console.log('⚠️  Please change all default passwords in production!')

  } catch (error) {
    console.error('❌ Database seeding failed:', error)
    process.exit(1)
  } finally {
    await prisma.$disconnect()
  }
}

// 运行种子脚本
seedDatabase().catch((error) => {
  console.error('❌ Seeding failed:', error)
  process.exit(1)
})
